package com.wenzhoujie.fragment;

import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wenzhoujie.library.customview.ClearEditText;
import com.wenzhoujie.library.utils.SDToast;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.wenzhoujie.LoginNewActivity;
import com.wenzhoujie.RegisterActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.LoginActModel;
import com.wenzhoujie.model.act.SyncloginActModel;
import com.wenzhoujie.umeng.UmengSocialManager;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

public class LoginFragment extends BaseFragment implements OnClickListener
{

	@ViewInject(id = R.id.act_login_ll_third_login)
	private LinearLayout mLlThridLogin = null;

	@ViewInject(id = R.id.act_login_ll_login_sina)
	private LinearLayout mLlLoginSina = null;

	@ViewInject(id = R.id.act_login_ll_login_qq)
	private LinearLayout mLlLoginQQ = null;

	@ViewInject(id = R.id.act_login_et_email)
	private ClearEditText mEtEmail = null;

	@ViewInject(id = R.id.act_login_et_pwd)
	private ClearEditText mEtPwd = null;

	@ViewInject(id = R.id.act_login_tv_login)
	private TextView mTvLogin = null;

	private String mStrUserName = null;
	private String mStrPassword = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_login, container, false);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		registeClick();
		initViewState();
	}

	private void initViewState()
	{
		String sinaAppKey = AppRuntimeWorker.getSina_app_key();
		String qqAppKey = AppRuntimeWorker.getQq_app_key();
		if (TextUtils.isEmpty(sinaAppKey) && TextUtils.isEmpty(qqAppKey))
		{
			mLlThridLogin.setVisibility(View.GONE);
		} else
		{
			if (TextUtils.isEmpty(sinaAppKey))
			{
				mLlLoginSina.setVisibility(View.GONE);
			}
			if (TextUtils.isEmpty(qqAppKey))
			{
				mLlLoginQQ.setVisibility(View.GONE);
			}
		}
	}

	private void registeClick()
	{
		mLlLoginSina.setOnClickListener(this);
		mLlLoginQQ.setOnClickListener(this);
		mTvLogin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_login_ll_login_sina:
			clickLoginSina();
			break;

		case R.id.act_login_ll_login_qq:
			clickLoginQQ();
			break;

		case R.id.act_login_tv_login:
			clickLoginNormal();
			break;

		default:
			break;
		}
	}

	/**
	 * 点击新浪微博登录,先获取个人资料，然后登录
	 */
	private void clickLoginSina()
	{
		UmengSocialManager.getUMLogin().doOauthVerify(getActivity(), SHARE_MEDIA.SINA, new UMAuthListener()
		{
			@Override
			public void onCancel(SHARE_MEDIA arg0)
			{
			}

			@Override
			public void onComplete(Bundle bundle, SHARE_MEDIA arg1)
			{
				final String uid = bundle.getString("uid");
				final String expires_in = bundle.getString("expires_in");
				final String access_token = bundle.getString("access_secret");
				UmengSocialManager.getUMLogin().getPlatformInfo(getActivity(), SHARE_MEDIA.SINA, new UMDataListener()
				{
					@Override
					public void onStart()
					{
						AppHelper.showLoadingDialog("请稍候...");
					}

					@Override
					public void onComplete(int code, Map<String, Object> data)
					{
						AppHelper.hideLoadingDialog();
						if (code == 200 && data != null)
						{
							requestSinaLogin(uid, expires_in, access_token, JSON.toJSONString(data));
						}

					}
				});
			}

			@Override
			public void onError(SocializeException arg0, SHARE_MEDIA arg1)
			{
				SDToast.showToast("授权失败");
			}

			@Override
			public void onStart(SHARE_MEDIA arg0)
			{
			}
		});
	}

	protected void requestSinaLogin(String uid, String expires_in, String access_token, String user_info)
	{
		RequestModel model = new RequestModel(false);
		model.put("act", "synclogin");
		model.put("login_type", "Sina");
		model.put("type", "android");
		model.put("sina_id", uid);
		model.put("access_token", access_token);
		model.put("user_info", user_info);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				SyncloginActModel actModel = JsonUtil.json2Object(responseInfo.result, SyncloginActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					int resultType = SDTypeParseUtil.getIntFromString(actModel.getResulttype(), 0);
					switch (resultType)
					{
					case -1: // 需要完善资料
						String sinaId = actModel.getSina_id();
						String sinaAccessToken = actModel.getAccess_token();
						if (!TextUtils.isEmpty(sinaId) && !TextUtils.isEmpty(sinaAccessToken))
						{
							Intent intent = new Intent(App.getApplication(), RegisterActivity.class);
							intent.putExtra(RegisterActivity.EXTRA_SINA_ID, sinaId);
							intent.putExtra(RegisterActivity.EXTRA_SINA_ACCESS_TOKEN, sinaAccessToken);
							startActivity(intent);
							getActivity().finish();
						}
						break;
					case 0: // 帐号被禁用
						SDToast.showToast("您的帐号已经被禁用");
						break;
					case 1: // 登录成功
						LocalUserModel.dealLoginSuccess(actModel.getUid(), actModel.getEmail(), actModel.getUser_name(), actModel.getUser_pwd(), actModel.getUser_avatar(), null,
								actModel.getUser_money(), actModel.getUser_money_format(), actModel.getUser_score(),actModel.getNick_name());
						getActivity().setResult(LoginNewActivity.RESULT_CODE_LOGIN_SUCCESS);
						getActivity().finish();
						break;

					default:
						break;
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	/**
	 * 点击qq登录,先获取个人资料
	 */
	private void clickLoginQQ()
	{
		UmengSocialManager.getUMLogin().doOauthVerify(getActivity(), SHARE_MEDIA.QQ, new UMAuthListener()
		{
			@Override
			public void onCancel(SHARE_MEDIA arg0)
			{
			}

			@Override
			public void onComplete(Bundle bundle, SHARE_MEDIA arg1)
			{
				final String openId = bundle.getString("openid");
				final String expires_in = bundle.getString("expires_in");
				final String access_token = bundle.getString("access_token");
				UmengSocialManager.getUMLogin().getPlatformInfo(getActivity(), SHARE_MEDIA.QQ, new UMDataListener()
				{
					@Override
					public void onStart()
					{
						AppHelper.showLoadingDialog("请稍候...");
					}

					@Override
					public void onComplete(int code, Map<String, Object> data)
					{
						AppHelper.hideLoadingDialog();
						if (code == 200 && data != null)
						{
							requestQQLogin(openId, expires_in, access_token, JSON.toJSONString(data));
						}
					}
				});
			}

			@Override
			public void onError(SocializeException arg0, SHARE_MEDIA arg1)
			{
				SDToast.showToast("授权失败");
			}

			@Override
			public void onStart(SHARE_MEDIA arg0)
			{
			}
		});

	}

	protected void requestQQLogin(String openId, String expires_in, String access_token, String user_info)
	{
		RequestModel model = new RequestModel(false);
		model.put("act", "synclogin");
		model.put("login_type", "Qq");
		model.put("type", "android");
		model.put("openid", openId);
		model.put("access_token", access_token);
		model.put("user_info", user_info);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				SyncloginActModel actModel = JsonUtil.json2Object(responseInfo.result, SyncloginActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					int resultType = SDTypeParseUtil.getIntFromString(actModel.getResulttype(), 0);
					switch (resultType)
					{
					case -1: // 需要完善资料
						String QQId = actModel.getQq_id();
						String QQAccessToken = actModel.getAccess_token();
						if (!TextUtils.isEmpty(QQId) && !TextUtils.isEmpty(QQAccessToken))
						{
							Intent intent = new Intent(App.getApplication(), RegisterActivity.class);
							intent.putExtra(RegisterActivity.EXTRA_QQ_ID, QQId);
							intent.putExtra(RegisterActivity.EXTRA_QQ_ACCESS_TOKEN, QQAccessToken);
							startActivity(intent);
							getActivity().finish();
						}
						break;
					case 0: // 帐号被禁用
						SDToast.showToast("您的帐号已经被禁用");
						break;
					case 1: // 登录成功
						LocalUserModel.dealLoginSuccess(actModel.getUid(), actModel.getEmail(), actModel.getUser_name(), actModel.getUser_pwd(), actModel.getUser_avatar(), null,
								actModel.getUser_money(), actModel.getUser_money_format(), actModel.getUser_score(),actModel.getNick_name());
						getActivity().setResult(LoginNewActivity.RESULT_CODE_LOGIN_SUCCESS);
						getActivity().finish();
						break;

					default:
						break;
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	private void clickLoginNormal()
	{
		if (validateParam())
		{
			RequestModel model = new RequestModel(false);
			model.put("act", "login");
			model.put("email", mStrUserName);
			model.put("pwd", mStrPassword);
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					LoginActModel actModel = JsonUtil.json2Object(responseInfo.result, LoginActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getResponse_code() == 1)
						{
							dealLoginNormalSuccess(actModel);
						}
					}
					//保存用户信息
					//final LocalUserModel user = App.getApplication().getmLocalUser();
					/*final LocalUserModel user = new LocalUserModel();
					user.setUser_name(mStrUserName);
					user.setUser_pwd(mStrPassword);
					App.getApplication().setmLocalUser(user);*/
					
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	protected void dealLoginNormalSuccess(LoginActModel actModel)
	{
		LocalUserModel.dealLoginSuccess(actModel.getUid(), actModel.getUser_email(), actModel.getUser_name(), mStrPassword, actModel.getUser_avatar(), null,
				actModel.getUser_money(), actModel.getUser_money_format(), actModel.getUser_score(),actModel.getNick_name());
		getActivity().setResult(LoginNewActivity.RESULT_CODE_LOGIN_SUCCESS);
		getActivity().finish();
	}

	private boolean validateParam()
	{
		mStrUserName = mEtEmail.getText().toString();
		if (TextUtils.isEmpty(mStrUserName))
		{
			SDToast.showToast("用户邮箱不能为空");
			mEtEmail.requestFocus();
			return false;
		}
		mStrPassword = mEtPwd.getText().toString();
		if (TextUtils.isEmpty(mStrPassword))
		{
			SDToast.showToast("密码不能为空");
			mEtPwd.requestFocus();
			return false;
		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case LoginNewActivity.REQUEST_CODE_REGISTER:
			if (resultCode == RegisterActivity.RESULT_CODE_REGISTER_SUCCESS)
			{
				String userName = data.getStringExtra(RegisterActivity.EXTRA_RESULT_USER_NAME);
				String pwd = data.getStringExtra(RegisterActivity.EXTRA_RESULT_PASSWORD);
				mEtEmail.setText(userName);
				mEtPwd.setText(pwd);
				clickLoginNormal();
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}